package com.wall.haven.util;

import com.wall.haven.constant.RegExConstants;
import org.springframework.http.MediaType;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;

/**
 * request工具类
 *
 * @author ChenWangKun
 * @date 2023-06-01
 **/

public class RequestUtil {

    /**
     * 获取请求体
     *
     * @param request
     * @return {@link String}
     * @author ChenWangKun
     * @date 2023/5/8
     */
    public static String getRequestBody(HttpServletRequest request) throws IOException {
        String requestBody = "";
        ContentCachingRequestWrapper wrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class);
        if (wrapper != null) {
            requestBody = new String(wrapper.getContentAsByteArray(), wrapper.getCharacterEncoding());
            //压缩json
            if (Objects.equals(wrapper.getContentType(), MediaType.APPLICATION_JSON_VALUE)) {
                requestBody = requestBody.replaceAll(RegExConstants.COMPRESS_JSON_REGEX, "");
            }
        }
        return requestBody;
    }
}
